package com.sohh.demo;

import java.util.List;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.stream.Collectors;

public class MergeUtil {
 
    /**
     * 把sourceList里面的一些属性合并到targetList里面
     * 基于testFunction的条件,合入逻辑实现为biConsumer
     *
     * @param targetList
     * @param sourceList
     * @param testFunction
     * @param biConsumer
     * @param <T>
     * @param <S> studentList,classroomList,
     *           (stu,room) -> stu.getRoomId() == room.getRoomId(),
     *           (stu,room) -> stu.setRoomName(room.getRoomName())
     */
    public static <T, S> void merge(List<T> targetList, List<S> sourceList, BiFunction<? super T, ? super S, Boolean> testFunction,
                                    BiConsumer<? super T, ? super S> biConsumer) {
 
        targetList.forEach((t)->{
            Optional<S> optional = sourceList.stream().filter(s->testFunction.apply(t, s)).findFirst();
            if (optional.isPresent()) {
                biConsumer.accept(t, optional.get());
            }
        });
 
    }
 
    /**
     * 把sourceList里面的一些item分类合并到targetList的每一个item里面
     *
     * @param targetList
     * @param sourceList
     * @param testFunction
     * @param biConsumer
     * @param <T>
     * @param <S>
     */
    public static <T, S> void mergeList(List<T> targetList, List<S> sourceList, BiFunction<? super T, ? super S, Boolean> testFunction,
                                    BiConsumer<? super T, ? super List<S>> biConsumer) {
 
        targetList.forEach((t)->{
            List<S> dataList = sourceList.stream().filter(s->testFunction.apply(t, s)).collect(Collectors.toList());
            Optional<List<S>> optional = Optional.of(dataList);
            if (optional.isPresent()) {
                biConsumer.accept(t, optional.get());
            }
        });
    }
}